﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CardInChina.Data.Entity.Entity;

namespace CardInChina.Data.Entity.Interface
{
    public class FavoriteService
    {
        private CICEntities _db = new CICEntities();

        public void AddFavorite(int customerID, int cardID)
        {
            using (CICEntities db = new CICEntities())
            {
                db.Favorites.Add(new Favorite { 
                    CardID = cardID,
                    CustomerID = customerID,
                    CreateDate = DateTime.Now,
                    LastModifyDate = DateTime.Now,
                    Disabled = false
                });
                db.SaveChanges();
            }

        }

        public void DeleteFavorite(int favoriteID)
        {
            using (CICEntities db = new CICEntities())
            {
                var fa = db.Favorites.FirstOrDefault(f => f.FavoriteID == favoriteID);
                fa.Disabled = true;
                db.SaveChanges();
            }
        }


        public Favorite GetFavoriteByCustomerIDAndCardID(int customerID, int cardID)
        {
            using (CICEntities db = new CICEntities())
            {
                return db.Favorites.FirstOrDefault(f => f.CardID == cardID && f.CustomerID == customerID);
            }
 
        }

        public List<Favorite> GetFavoritesByCustomerID(int customerID)
        {
            var customer = _db.Customers.FirstOrDefault(c => c.CustomerID == customerID);
            if (customer == null) throw new Exception("customer not found!");
            List<Favorite> cards = new List<Favorite>();
            foreach(var f  in customer.OfFavorites.Where(f => !f.Disabled && f.OfCard != null)){
                cards.Add(f);
            }
            return cards;
        }
    }
}

